#Java - Code Snippets for '#String contains' - 4 code snippet(s) found |
|
Sample 1. Check if a string contains a substring. | |
|
String text = "I don't think we're in Kansas anymore";
if(text.indexOf("Kansas") != -1){
System.out.println("Yes, the dialog contains Kansas");
}
|
|
Like Feedback string substring indexOf() |
|
|
Sample 2. Remove Alien characters i.e removing everything except characters , numbers and special characters. | |
|
String removeAlienCharacters(String str){
String newString = new String();
String returnString = "";
if(str.contains("<")){
String[] str2 = str.split("<");
str = str2[0];
}
for(char x: str.toCharArray()){
if((x >= 48 && x <= 57) || (x>=65 && x <= 90) || (x >= 97 && x<= 122) || x=='.'){
returnString += x;
}
}
return returnString.trim();
}
|
|
Like Feedback string .contains() .split() string split string contains remove characters from string remove alien characters |
|
|
Sample 3. Method to get a map of words and their count by passing in the string | |
|
Map<String,Integer> wordCountMap = new TreeMap();
String[] words = text.split(" ");
Set<Integer> countSet;
for(String word: words) {
if(wordCountMap.containsKey(word.toLowerCase())){
wordCountMap.put(word.toLowerCase(), wordCountMap.get(word.toLowerCase()).intValue() + 1);
} else {
wordCountMap.put(word.toLowerCase(), 1);
}
}
countSet = new TreeSet(Collections.reverseOrder());
countSet.addAll(wordCountMap.values());
for(Integer inte: countSet) {
for(Entry<String,Integer> entry: wordCountMap.entrySet()){
if(entry.getValue() == inte) {
System.out.println(entry);
}
}
}
|
|
Like Feedback map word count map of string and integer containsKey string split treeset Collections.reverseOrder set addAll entry |
|
|
Sample 4. Check if the String contains specified characters using CharSetUtils (Apache Commons) | |
|
System.out.println(CharSetUtils.containsAny("Whats Up ?", "W")); // Prints true as the String contains character W System.out.println(CharSetUtils.containsAny("Whats Up ?", "YZ")); // Prints false as the String doesn't contain character Y or Z
|
|
Like Feedback CharSetUtils (Apache Commons) Check if String contains characters |
|
|